package com.hh.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author yangfan
 * @date 2020/2/19 17:22
 * @description 解决跨域请求问题
 */
@Configuration
public class HhCorsConfiguration {

    /**
     * @description 注入CorsFilter实例
     * @return org.springframework.web.filter.CorsFilter
     */
    @Bean
    public CorsFilter corsFilter(){

        //初始化配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许跨域的域名，若要携带cookie，不能设置为*：全部域名
        corsConfiguration.addAllowedOrigin("*");
        //允许携带cookie
        corsConfiguration.setAllowCredentials(false);
        //允许所有请求方法
        corsConfiguration.addAllowedMethod("*");
        //允许携带任何头信息
        corsConfiguration.addAllowedHeader("*");

        //初始化配置源对象
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsFilter(corsConfigurationSource);
    }
}
